package com.googlecode.duplicatedetector.model;

import java.io.File;
import java.util.regex.Pattern;

public class RegexFilter implements Filter {

	private Pattern[] include;
	private Pattern[] exclude;

	public RegexFilter(String toInclude, String toExclude) {
		String[] includes = toInclude.split(",");
		include = new Pattern[includes.length];
		for (int i = 0; i < includes.length; i++) {
			include[i] = Pattern.compile(process(includes[i]));
		}
		if (include.length == 0) {
			include = new Pattern[] { Pattern.compile(".*") };
		}
		String[] excludes = toExclude.split(",");
		exclude = new Pattern[excludes.length];
		for (int i = 0; i < excludes.length; i++) {
			exclude[i] = Pattern.compile(process(excludes[i]));
		}
	}

	@Override
	public boolean accept(File file) {
		for (Pattern i : include) {
			if (i.matcher(file.getAbsolutePath()).matches()) {
				for (Pattern e : exclude) {
					if (e.matcher(file.getAbsolutePath()).matches()) {
						return false;
					}
				}
				return true;
			}
		}
		return false;
	}

	private String process(String filter) {
		String processed = filter.trim();
		processed = processed.replaceAll("\\.", "\\\\.").replaceAll("\\?",
				".{1}").replaceAll("\\*", ".*?");
		return processed;
	}

}
